package cn.com.idmy.cloud.config;


import cn.com.idmy.base.config.DefaultConfig;
import cn.com.idmy.base.util.Assert;
import cn.com.idmy.cloud.config.DruidPoolConfig.DruidProfile;
import com.alibaba.fastjson2.JSON;
import org.dromara.hutool.core.lang.Console;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Objects;
import java.util.Properties;

import static java.text.MessageFormat.format;

public class SpringEnvProps {
    static {
        JSON.config(DefaultConfig.jsonWriterFeatures);
    }

    @NotNull
    public static String toEnv(@Nullable String active) {
        if (active != null) {
            if (active.startsWith("prod")) {
                return "prod";
            } else if (active.startsWith("dev")) {
                return "dev";
            } else if (active.startsWith("pre")) {
                return "pre";
            } else if (active.startsWith("test")) {
                return "test";
            }
        }
        return "local";
    }

    @NotNull
    public static Properties getProps(@NotNull ConfigurableEnvironment env) {
        var active = env.getProperty("spring.profiles.active");
        Console.error("spring.profiles.active：{}", active);
        if (active == null) {
            var activeProfiles = env.getActiveProfiles();
            if (activeProfiles.length > 0) {
                active = activeProfiles[0];
            }
            Console.error("activeProfiles：{}", active);
        }
        var appEnv = toEnv(active);
        var appKey = Assert.notBlank(env.getProperty("spring.application.name"), "没有应用名");
        Assert.notBlank(active, "请使用「application-****.yml」启动");

        System.setProperty("app.key", appKey);
        System.setProperty("app.env", appEnv);
        System.setProperty("app.port", Objects.requireNonNull(env.getProperty("server.port")));

        var props = new Properties();
        props.setProperty("spring.cloud.nacos.discovery.namespace", active);
        props.setProperty("spring.cloud.nacos.discovery.server-addr", "localhost:8848");
        props.setProperty("server.port", "0");
        props.setProperty("logging.level.root", "info");
        props.setProperty("logging.file.name", format("/logs/{0}.log", appKey));
        var druidProfile = env.getProperty("druid.config.profile", "auto");
        if (appEnv.equals("local")) {
            SpringEnvDruidProps.addProps(props, DruidPoolConfig.calculate(DruidProfile.of("local")));
        } else {
            SpringEnvDruidProps.addProps(props, DruidPoolConfig.calculate(DruidProfile.of(druidProfile)));
        }
        SpringEnvDruidProps.addProps(props);
        Console.error("配置：{} = {}", "appKey", appKey);
        Console.error("配置：{} = {}", "active", active);
        Console.error("配置：{} = {}", "env", appEnv);
        return props;
    }
}
